package org.base23.uaa.authorization.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.base23.uaa.business.service.JwtService;
import org.base23.uaa.business.service.RoleMenuPermissionService;
import org.base23.uaa.core.domain.dto.CurrentUser;
import org.base23.web.exception.Exceptions;
import org.base23.web.model.Result;
import org.base23.web.model.ResultBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/internal/api-auth")
@Tag(name = "内部认证API", description = "用于服务间认证授权的内部接口")
public class ApiAuthController {

  @Autowired
  private JwtService jwtService;

  @Autowired
  private RoleMenuPermissionService roleMenuPermissionService;

  @GetMapping
  @Operation(summary = "校验API权限", description = "验证token并返回用户信息与权限列表")
  public Result checkApiAuth(HttpServletRequest request) {
    String jwtToken = request.getHeader("Authorization");
    if (jwtToken == null || jwtToken.isEmpty()) {
      Exceptions.throwException("Authorization header is empty!");
    }
    if (jwtToken.startsWith("Bearer ")) {
      jwtToken = jwtToken.substring(7);
    }

    // 校验token
    CurrentUser currentUser = jwtService.verifyJwt(jwtToken, CurrentUser.class);
    Set<String> permissions = roleMenuPermissionService.getRoleMenuPermissionCodes(
        currentUser.getRoleCode());

    Map<String, Object> rspData = new HashMap<>();
    rspData.put("user", currentUser);
    rspData.put("permissions", permissions);

    return ResultBuilder.aResult()
        .code(Result.SUCCESS_CODE)
        .msg("OK")
        .data(rspData)
        .build();
  }

}
